package com.logicbus.dbcp.util;

import com.google.re2j.Matcher;
import com.google.re2j.Pattern;
import com.logicbus.dbcp.sql.RowRenderer;

import java.sql.ResultSetMetaData;
import java.util.HashMap;
import java.util.Map;

/**
 * 从sql中获取列的别名，在输出时转换原列名输出
 *
 * @param <T>
 *
 * @since 1.6.13.5 [20200605 duanyy]
 */
public class ColumnIdRowRenderer<T> implements RowRenderer<T> {
    protected IdMapper idMapper = null;
    public ColumnIdRowRenderer(String sql){
        idMapper = new IdMapper(sql);
    }
    public String getColumnId(ResultSetMetaData metadata, int index) {
        try {
            String name = metadata.getColumnLabel(index);
            if (name == null){
                name = metadata.getColumnName(index);
            }
            return idMapper != null ? idMapper.getColumnId(name):name;
        }catch (Exception ex){
            return null;
        }
    }

    public Map<String, T> render(Map<String, T> rowData) {
        return rowData;
    }

    public Map<String,T> newRow(int columnCount){
        return new HashMap<String,T>(columnCount);
    }

    public static class IdMapper {
        private Map<String,String> mapping = new HashMap<String,String>();
        protected Pattern columns = Pattern.compile("([sS][eE][lL][eE][cC][tT])(.*?)([fF][rR][oO][mM])");
        protected Pattern pattern = Pattern.compile("([0-9A-Za-z_]*[A-Z]+[0-9A-Za-z_]*)");
        public IdMapper(String sql){
            parseSql(sql);
        }

        public String getColumnId(String columnId){
            String found = mapping.get(columnId);
            return found == null ? columnId:found;
        }

        private void parseSql(String sql) {
            Matcher columnList = columns.matcher(sql);
            while (columnList.find()){
                Matcher matcher = pattern.matcher(columnList.group(2));
                while (matcher.find()){
                    String id = matcher.group(1);
                    mapping.put(id.toLowerCase(),id);
                }
            }
        }
    }
}